<?php
include '../../startup.php';
include '../../model/user.php';

header('Content-Type: application/json; charset=utf-8');

// handle actions
switch ($_act) {
	case 'add' :
		if ($_form->userHasFunction('add')) {
			if (isset($_POST['relatedusername']) || !empty($_POST['relatedusername'])) 
			{
				$val = validateInputRelated();
				if ($val=='ok') {
					$res = addUserRelated($_POST);
					$_response['status'] = 1;
					$_response['message'] = sprintf(MSG_ADD_ITEM_SUCCESS,3);
					$_response['redirect'] = HTTPS_SERVER.'forms/admin/user_list.php';
					$_response['redirect-time'] = 3000;
				} else {
					$_response['status'] = 0;
					$_response['message'] = MSG_ERROR_FIELDS.$val;
				}
			} else {
				$val = validateInputIndie();
				if ($val=='ok') {
					$res = addUserIndie($_POST);
					$_response['status'] = 1;
					$_response['message'] = sprintf(MSG_ADD_ITEM_SUCCESS,3);
					$_response['redirect'] = HTTPS_SERVER.'forms/admin/user_list.php';
					$_response['redirect-time'] = 3000;
				} else {
					$_response['status'] = 0;
					$_response['message'] = MSG_ERROR_FIELDS.$val;
				}
			}
		} else {
				$_response['status'] = 0;
				$_response['message'] = MSG_TASK_NOT_AUTHORIZED;
		}
		break;
}

echo json_encode($_response);


/// SUPPORTING FUNCTIONS
function validateInputIndie(){
	global $_POST;
	$err = array();
	if (!isset($_POST['username']) || empty($_POST['username'])) {
		$err[] = '<li>Username must be filled</li>';
	}
	if (!isset($_POST['displayname']) || empty($_POST['displayname'])) {
		$err[] = '<li>User display name must be filled</li>';
	}
	if (!isset($_POST['password']) || empty($_POST['password'])) {
		$err[] = '<li>User password must be filled</li>';
	}
	if (!isset($_POST['begineff']) || empty($_POST['begineff'])) {
		$err[] = '<li>Begin effective date must be filled</li>';
	}
	if (!isset($_POST['lasteff']) || empty($_POST['lasteff'])) {
		$err[] = '<li>Last effective date must be filled</li>';
	}
	
	if (count($err)>0) {
		return '<ul>'.implode('',$err).'</ul>';
	} else return 'ok';
}

function validateInputRelated(){
	global $_POST;
	$err = array();
	if (!isset($_POST['relatedusername']) || empty($_POST['relatedusername'])) {
		$err[] = '<li>Username from fingerprint machine must be filled</li>';
	}
	if (!isset($_POST['password']) || empty($_POST['password'])) {
		$err[] = '<li>User password must be filled</li>';
	}
	if (!isset($_POST['begineff']) || empty($_POST['begineff'])) {
		$err[] = '<li>Begin effective date must be filled</li>';
	}
	if (!isset($_POST['lasteff']) || empty($_POST['lasteff'])) {
		$err[] = '<li>Last effective date must be filled</li>';
	}
	
	if (count($err)>0) {
		return '<ul>'.implode('',$err).'</ul>';
	} else return 'ok';
}


?>